import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './router'
import store from '../store/index'
import { getCookie } from '@/utils/aqi'

Vue.use(VueRouter)

const isCustomerPath = window.location.pathname.includes('/customer/web')
const basePath = isCustomerPath ? '/customer/web' : '/web/cmsview/crm' // 根据当前路径动态选择基础路径

const router = new VueRouter({
  mode: 'history',
  base: basePath, // 动态设置基础路径
  routes
})

// 封装添加路由
const addRout = (item) => {
  router.addRoutes(item)
}

var num = 0
router.beforeEach((to, from, next) => {
  if (to.path === '/Login') {
    next()
  } else {
    if (to.matched.length === 0) {
      if (num < 4) {
        setTimeout(() => {
          addRout(store.state.module1.menu_list)
          next({ ...to, replace: true })
          num = num + 1
        }, 500)
      } else {
        num = 0
        if (getCookie('token')) {
          // 根据当前路径判断跳转到正确的首页
          if (window.location.pathname !== `${basePath}/Home`) {
            window.location.href = `${basePath}/Home`
          }
        } else {
          window.location.href = `${basePath}/Login`
        }
      }
    } else {
      next()
    }
  }
})

export default router
